Validating user input in java

chris (2004-05-09 12:53:50)
3486 views
0 replies
I have a basic pattern matching shell for a validation class which I have been using for the last few weeks on an application. It uses java's regular expression package in java.util.regex to pattern match strings against regular expressions. It's quite simple. This is how it's used:
// instantiate the Validator class
Validator validator = new Validator();

// call whichever method you want to use - depending on what your validating
// here I'm just checking that the string contains numbers only

if(!validator.checkNumber(numberString)){
      // do something if you fancy
      return;
}

// you'll only get this far if the validation was successful


And here's a copy of the full Validator class definition:

import java.util.regex.*;

/*
 * Validator.java
 */

/**
 * $Id$
 * @author  Administrator
 */

public class Validator {
    private String regex;
    private Pattern pattern;
    private Matcher matcher;
    
    /** Creates a new instance of Validator */
    public Validator() {
    }
    
    public boolean checkName(String name){
        //System.out.println(" sent in name string: "+name);
        regex = ".*[^s]{1,}.*"; // anything, then at least one non whitespace charater, then anything
        pattern = Pattern.compile(regex);
        return(pattern.matcher(name).matches());
    }
    
    public boolean checkNumber(String number){
        /* check that there is a valid number */
        regex = ".*d+.*"; // any numbers (greedy & lazy)
        pattern = Pattern.compile(regex);
        return(pattern.matcher(number).matches());
    }
    
    public boolean checkEmail(String email){
        /* check that there is a valid number */
        pattern = Pattern.compile(".+@.+.[a-z]+"); // inclusive character class
        if(!pattern.matcher(email).matches()){
            // no valid characters
            return false;
        }else{
            return true;
        }        
    }
}

I know my regular expressions are a bit sloppy, but hey..

christo
comment